// SPDX-FileCopyrightText: Copyright 2025-2025 深圳市同心圆网络有限公司
// SPDX-License-Identifier: GPL-3.0-only

package config

import (
	"os"

	"gitcode.com/opendragonfly/df_server/utils"
	"gopkg.in/yaml.v3"
)

type PortConfig struct {
	ServicePort          uint16 `yaml:"servicePort"`
	EnableZipkin         bool   `yaml:"enableZipkin"`
	ZipkinPort           uint16 `yaml:"zipkinPort"`
	EnableJaegerGrpc     bool   `yaml:"enableJaegerGrpc"`
	JaegerGrpcPort       uint16 `yaml:"jaegerGrpcPort"`
	EnableJaegerHttp     bool   `yaml:"enableJaegerHttp"`
	JaegerHttpPort       uint16 `yaml:"jaegerHttpPort"`
	EnableSkywalkingGrpc bool   `yaml:"enableSkywalkingGrpc"`
	SkywalkingGrpcPort   uint16 `yaml:"skywalkingGrpcPort"`
	EnableSkywalkingHttp bool   `yaml:"enableSkywalkingHttp"`
	SkywalkingHttpPort   uint16 `yaml:"skywalkingHttpPort"`
	EnableOtlpGrpc       bool   `yaml:"enableOtlpGrpc"`
	OtlpGrpcPort         uint16 `yaml:"otlpGrpcPort"`
	EnableOtlpHttp       bool   `yaml:"enableOtlpHttp"`
	OtlpHttpPort         uint16 `yaml:"otlpHttpPort"`
}

type RemoteConfig struct {
	RemoteId    string `yaml:"remoteId"`
	RemoteAddr  string `yaml:"remoteAddr"`
	ProjectId   string `yaml:"projectId"`
	ShareSecret string `yaml:"shareSecret"`
}

type ServerConfig struct {
	KeepTraceDay uint            `yaml:"keepTraceDay"`
	SuperToken   string          `yaml:"superToken"`
	Port         PortConfig      `yaml:"port"`
	RemoteList   []*RemoteConfig `yaml:"remoteList"`
}

func (cfg *ServerConfig) GetRemote(remoteId string) (*RemoteConfig, bool) {
	for _, remoteCfg := range cfg.RemoteList {
		if remoteCfg.RemoteId == remoteId {
			return remoteCfg, true
		}
	}
	return nil, false
}

func ReadServerConfig() (*ServerConfig, error) {
	data, err := os.ReadFile(utils.CONFIG_FILE_PATH)
	if err != nil {
		return nil, err
	}
	cfg := &ServerConfig{}
	err = yaml.Unmarshal(data, cfg)
	if err != nil {
		return nil, err
	}
	if cfg.RemoteList == nil {
		cfg.RemoteList = []*RemoteConfig{}
	}
	if cfg.KeepTraceDay == 0 {
		cfg.KeepTraceDay = 7
	}
	return cfg, nil
}

func WriteServerConfig(cfg *ServerConfig) error {
	if cfg.RemoteList == nil {
		cfg.RemoteList = []*RemoteConfig{}
	}
	err := utils.InitUserAndGroup()
	if err != nil {
		return err
	}
	data, err := yaml.Marshal(cfg)
	if err != nil {
		return err
	}
	err = os.WriteFile(utils.CONFIG_FILE_PATH, data, 0644)
	if err != nil {
		return err
	}
	uid, gid, err := utils.GetUidAndGid()
	if err == nil {
		os.Chown(utils.CONFIG_FILE_PATH, uid, gid) //skip error check
	}
	return nil
}
